<template>
  <div class="master-basic-info">
    <div class="m-h3-btn-box border margin-top30">
      <h3>校长信息</h3>
      <div class="u-btn-box">
        <el-button
          type="primary"
          @click="addMaster('add')"
          size="small"
          v-if="!masterId"
          >{{ !isSchoolMasterSave ? '新增' : '保存' }}
        </el-button>
        <el-button type="primary" @click="addMaster()" size="small" v-else>
          {{ isSchoolMasterSave ? '保存' : '编辑' }}</el-button
        >
      </div>
    </div>
    <el-form
      :model="schoolMaster"
      label-width="100px"
      label-position="left"
      :rules="schoolMasterRules"
      ref="schoolMaster"
      v-if="isMasterShow"
    >
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="" prop="imageUrl">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :http-request="uploadMasterImg"
              :before-upload="beforeMasterAvatarUpload"
            >
              <img
                v-if="schoolMaster.headUrl"
                :src="schoolMaster.headUrl"
                class="avatar"
              />
              <span
                class="el-upload-list__item-delete"
                @click.stop="handleMasterRemove()"
                v-if="schoolMaster.headUrl"
                >x</span
              >
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="姓名：" prop="realName">
                <el-input
                  v-model="schoolMaster.realName"
                  placeholder="请输入姓名"
                  clearable
                  :disabled="!isSchoolMasterSave"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="账号：" prop="username">
                <el-input
                  v-model="schoolMaster.username"
                  placeholder="请输入账号"
                  clearable
                  :disabled="!isSchoolMasterSave"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="性别：" prop="sex">
                <el-select
                  v-model="schoolMaster.sex"
                  placeholder="请选择性别"
                  :disabled="!isSchoolMasterSave"
                >
                  <el-option label="男" :value="0"></el-option>
                  <el-option label="女" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="年龄：" prop="age">
                <el-input
                  v-model="schoolMaster.age"
                  placeholder="请输入年龄"
                  clearable
                  :disabled="!isSchoolMasterSave"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="联系方式：" prop="mobile">
                <el-input
                  v-model="schoolMaster.mobile"
                  placeholder="请输入联系方式"
                  clearable
                  :disabled="!isSchoolMasterSave"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="授课年级：" prop="grade">
                <nice-select
                  v-model="schoolMaster.grade"
                  placeholder="请选择年级"
                  clearable
                  :disabled="!isSchoolMasterSave"
                  :options="selectEnums.grade"
                  labelkey="name"
                  valuekey="id"
                ></nice-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="学科：" prop="subjects">
                <nice-select
                  v-model="schoolMaster.subjects"
                  placeholder="请选择学科"
                  clearable
                  multiple
                  :disabled="!isSchoolMasterSave"
                  :options="selectEnums.subject"
                  labelkey="name"
                  valuekey="id"
                ></nice-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="教学理念：" prop="teacherMotto">
                <el-input
                  type="textarea"
                  maxlength="200"
                  v-model="schoolMaster.teacherMotto"
                  placeholder="请输入教学理念"
                  clearable
                  :disabled="!isSchoolMasterSave"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import { ossUpload, tableUpdate } from '@/api/api.js'
import { addPrincipalInfo } from '@/api/user.js'
export default {
  props: {
    url: {
      type: String,
      default: ''
    },
    masterInfo: {
      type: Object,
      default: function () {
        return {}
      }
    },
    selectEnums: {
      type: Object,
      default: function () {
        return {}
      }
    },
    gradeList: {
      type: Array,
      default: function () {
        return []
      }
    },
    masterId: '',
    schoolId: ''
  },
  watch: {
    masterInfo: {
      handler (val) {
        console.log(JSON.stringify(val))
        if (JSON.stringify(val) !== '{}') {
          this.isSchoolMasterSave = false
          this.isMasterShow = true
          this.schoolMaster.realName = val.realName
          this.schoolMaster.headUrl = val.headUrl || ''
          this.schoolMaster.grade = val.grade || ''
          this.schoolMaster.subjects = val.subjectList || []
          this.schoolMaster.username = val.username || ''
          this.schoolMaster.age = val.age || ''
          this.schoolMaster.mobile = val.mobile || ''
          this.schoolMaster.sex = val.sex === 2 ? '' : val.sex
          this.schoolMaster.teacherMotto = val.teacherMotto || ''
          this.schoolMaster.schoolId = this.schoolId || ''
          this.$nextTick(() => {
            this.$refs['schoolMaster'].clearValidate()
          })
        } else {
          this.isMasterShow = false
        }
      },
      deep: true,
      immediate: true
    }
    // masterId(val, oldval) {
    //   this.isMasterShow = !!val;
    // },
  },
  data () {
    return {
      schoolMaster: {
        realName: '',
        username: '',
        age: '',
        mobile: '',
        sex: '',
        grade: '',
        subjects: [],
        headUrl: '',
        teacherMotto: ''
      },
      isMasterShow: false,
      isSchoolMasterSave: false,
      schoolMasterRules: {
        realName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '年龄不能为空', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value) {
                if (!/^([1-9][0-9]{0,1}|100)$/.test(value)) {
                  callback('请输入1到100之间的数字！') //eslint-disable-line
                } else {
                  callback()
                }
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],

        sex: [{ required: true, message: '性别不能为空', trigger: 'change' }],
        mobile: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '授课年级不能为空', trigger: 'change' }
        ],
        subjects: [
          { required: true, message: '学科不能为空', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    async uploadMasterImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'MASTER_PORTRAIT')
      if (res[0]) {
        return
      }
      this.schoolMaster.headUrl = res[1].data.url
    },
    beforeMasterAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    schoolMasterSave () {
      if (this.isSchoolMasterSave) {
        this.$refs['schoolMaster'].validate(valid => {
          if (valid) {
            this.editMaster()
          }
        })
      } else {
        this.isSchoolMasterSave = true
      }
    },
    handleMasterRemove () {
      this.schoolMaster.headUrl = ''
    },
    addMaster (type) {
      if (this.isSchoolMasterSave) {
        this.$refs['schoolMaster'].validate(valid => {
          if (valid) {
            this.addMasterInfo()
          }
        })
      } else {
        this.isSchoolMasterSave = true
        this.isMasterShow = true
        if (type == 'add') {
          this.schoolMaster.realName = ''
          this.schoolMaster.headUrl = ''
          this.schoolMaster.grade = ''
          this.schoolMaster.subjects = []
          this.schoolMaster.username = ''
          this.schoolMaster.age = ''
          this.schoolMaster.mobile = ''
          this.schoolMaster.sex = ''
          console.log(this.schoolMaster)
          this.$nextTick(() => {
            this.$refs['schoolMaster'].resetFields()
          })
        }
      }
    },
    async addMasterInfo () {
      let arg = {
        ...this.schoolMaster,
        subjects: this.schoolMaster.subjects
          ? this.schoolMaster.subjects.join(',')
          : '',
        schoolId: this.schoolId
      }
      if (!this.schoolMaster.mobile) {
        delete arg['mobile']
      }
      let res = await addPrincipalInfo(arg)
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.$message.success('更新校长信息成功')
        this.$emit('refreshData')
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async editMaster () {
      let argObj = {
        sex: this.schoolMaster.sex,
        realName: this.schoolMaster.realName,
        age: this.schoolMaster.age,
        head_url: this.schoolMaster.headUrl,
        mobile: this.schoolMaster.mobile
      }
      let res = await tableUpdate([
        {
          table_name: 'sys_user',
          update: [
            {
              username: this.schoolMaster.username,
              sys_user_nice_user_base: [argObj],
              sys_user_nice_teacher_info: [
                {
                  speaker_subject: this.schoolMaster.subject || null,
                  speaker_grade: this.schoolMaster.grade || null
                }
              ]
            }
          ],
          where: [
            {
              user_id: this.masterId
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.$message.success('编辑校长信息成功')
        this.isSchoolMasterSave = false
        this.$emit('refreshData')
      } else {
        this.$message.error(res[1].msg)
      }
    }
  }
}
</script>
<style scoped></style>
